import imaplib
import email
from email.header import decode_header

# QQ邮箱的配置
EMAIL = "2770135510@qq.com"
PASSWORD = "jmenwnarpohtdeeg"
IMAP_SERVER = "imap.qq.com"

def decode_text(text, encodings):
    for encoding in encodings:
        try:
            return text.decode(encoding)
        except (UnicodeDecodeError, TypeError):
            continue
    return text.decode("utf-8", errors="ignore")  # 默认回退到UTF-8并忽略错误

def connect_to_qq_email():
    encodings = ["utf-8", "gbk", "iso-8859-1", "ascii"]
    
    try:
        # 连接到QQ邮箱IMAP服务器
        mail = imaplib.IMAP4_SSL(IMAP_SERVER)
        mail.login(EMAIL, PASSWORD)
        mail.select("inbox")
        
        # 搜索所有邮件
        status, messages = mail.search(None, "ALL")
        mail_ids = messages[0].split()
        
        for email_id in mail_ids:
            # 获取邮件内容
            status, msg_data = mail.fetch(email_id, "(RFC822)")
            raw_email = msg_data[0][1]
            
            # 尝试逐行解码
            email_message = email.message_from_bytes(raw_email)
            
            # 提取邮件内容
            subject, encoding = decode_header(email_message["Subject"])[0]
            if isinstance(subject, bytes):
                subject = decode_text(subject, encodings)
                    
            from_ = email_message.get("From")

            print(f"From: {from_}, Subject: {subject}")
            
        mail.logout()
    except Exception as e:
        print("无法连接到QQ邮箱:", str(e))

if __name__ == "__main__":
    connect_to_qq_email()
